// pages/index/index.js
const { getIndexConfig } = require('../../api/api.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        checkInDate: '',
        checkOutDate: '',
        checkInDay: '',
        checkOutDay: '',
        nights: 0,
        selectedDateRange: null,
        navBarHeight: 0,
        tabBarHeight: 0,
        contentHeight: 0,
        isImageAnimating: true, // 控制图片动画的开关

        // 民宿故事列表
        storyList: [{
                id: 1,
                title: '山间晨雾',
                description: '清晨时分，薄雾缭绕在山间，仿佛身处仙境。这里的每一个清晨都是大自然的馈赠。',
                date: '2024年春',
                image: 'https://image.shengxuankj.com/fronts/taleImage.png'
            },
            {
                id: 2,
                title: '四季更迭',
                description: '春有百花秋有月，夏有凉风冬有雪。在这里，你可以感受到最纯粹的四季变化。',
                date: '2024年夏',
                image: 'https://image.shengxuankj.com/fronts/taleImage02.png'
            },
            {
                id: 3,
                title: '星空物语',
                description: '远离城市的喧嚣，在这里可以看到最美的星空。每一颗星星都在诉说着古老的故事。',
                date: '2024年秋',
                image: 'https://image.shengxuankj.com/fronts/taleImage03.png'
            }
        ],
        showCalendarPopup: false,
        calendarDataMap: new Map(),
        isShow: false,
        today: new Date().getTime(),
        maxDate: new Date(new Date().getFullYear() + 1, new Date().getMonth(), new Date().getDate()).getTime(), // 一年后
        formatter: (day) => {
            const y = day.date.getFullYear();
            const m = String(day.date.getMonth() + 1).padStart(2, '0');
            const d = String(day.date.getDate()).padStart(2, '0');
            const dateStr = `${y}-${m}-${d}`;
            
            // 禁用过去的日期
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            if (day.date < today) {
                day.type = 'disabled';
                day.bottomInfo = '不可选';
            }
            
            return day;
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }

        // 初始化默认日期（今天和明天）
        this.initDefaultDates();
        
        // 计算剩余可视高度
        this.calculateContentHeight();

        // 使用统一 API 封装调用首页配置
        getIndexConfig({}, { showLoading: true })
          .then((res) => {
            console.log('首页配置接口返回：', res)
            this.setData({ indexConfig: res.data || null })
          })
          .catch((err) => {
            console.error('首页配置接口错误：', err)
          })
    },

    /**
     * 计算主要内容区域的高度
     */
    calculateContentHeight() {
        const systemInfo = wx.getWindowInfo();
        const windowHeight = systemInfo.windowHeight;
        const safeAreaBottom = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0;
        const tabBarHeight = 50 + safeAreaBottom; // 自定义tabbar高度(100rpx转px约50px) + 安全区域

        // 首页导航栏不占用空间，所以内容高度就是窗口高度减去tabbar高度
        const contentHeight = windowHeight;

        this.setData({
            tabBarHeight: tabBarHeight,
            contentHeight: contentHeight
        });
    },

    // 日期选择相关
    showCalendar() {
        this.setData({
            showCalendarPopup: true
        });
    },
    onConfirmDate(event) {
        const selectedDates = event.detail;
        if (selectedDates && selectedDates.length === 2) {
            const checkInDate = selectedDates[0];
            const checkOutDate = selectedDates[1];
            
            // 验证日期有效性
            if (!this.validateDateRange(checkInDate, checkOutDate)) {
                return;
            }
            
            // 计算入住天数
            const nights = this.calculateNights(checkInDate, checkOutDate);
            
            this.setData({
                selectedDateRange: selectedDates,
                checkInDate: this.formatDisplayDate(checkInDate),
                checkOutDate: this.formatDisplayDate(checkOutDate),
                checkInDay: this.getWeekDay(checkInDate),
                checkOutDay: this.getWeekDay(checkOutDate),
                nights: nights,
                showCalendarPopup: false
            });
            
            // 显示成功提示
            wx.showToast({
                title: `已选择${nights}晚住宿`,
                icon: 'success',
                duration: 1500
            });
        } else {
            wx.showToast({
                title: '请选择完整的日期范围',
                icon: 'none',
                duration: 2000
            });
        }
    },
    formatDateFun(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${(date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`;
    },

    // 初始化默认日期
    initDefaultDates() {
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        
        const nights = this.calculateNights(today, tomorrow);
        
        this.setData({
            selectedDateRange: [today, tomorrow],
            checkInDate: this.formatDisplayDate(today),
            checkOutDate: this.formatDisplayDate(tomorrow),
            checkInDay: this.getWeekDay(today),
            checkOutDay: this.getWeekDay(tomorrow),
            nights: nights
        });
    },

    // 格式化显示日期（如：07月07日）
    formatDisplayDate(date) {
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${month}月${day}日`;
    },

    // 获取星期几
    getWeekDay(date) {
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return weekDays[date.getDay()];
    },

    // 计算入住天数
    calculateNights(checkInDate, checkOutDate) {
        const timeDiff = checkOutDate.getTime() - checkInDate.getTime();
        return Math.ceil(timeDiff / (1000 * 3600 * 24));
    },

    // 验证日期范围
    validateDateRange(checkInDate, checkOutDate) {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // 检查入住日期不能是过去
        if (checkInDate < today) {
            wx.showToast({
                title: '入住日期不能早于今天',
                icon: 'none',
                duration: 2000
            });
            return false;
        }
        
        // 检查离店日期必须晚于入住日期
        if (checkOutDate <= checkInDate) {
            wx.showToast({
                title: '离店日期必须晚于入住日期',
                icon: 'none',
                duration: 2000
            });
            return false;
        }
        
        // 检查入住天数不能超过30天
        const nights = this.calculateNights(checkInDate, checkOutDate);
        if (nights > 30) {
            wx.showToast({
                title: '入住天数不能超过30天',
                icon: 'none',
                duration: 2000
            });
            return false;
        }
        
        return true;
    },

    // 通用关闭弹窗
    onClosePopup() {
        this.setData({
            showGenderPopup: false,
            showCalendarPopup: false
        });
    },

    /**
     * 预订按钮点击事件
     */
    onBooking() {
        // 检查是否已选择日期
        if (!this.data.selectedDateRange || this.data.selectedDateRange.length !== 2) {
            wx.showToast({
                title: '请先选择入住日期',
                icon: 'none',
                duration: 2000
            });
            this.showCalendar();
            return;
        }
        
        // 构建查询参数
        const checkInDate = this.formatDateFun(this.data.selectedDateRange[0]);
        const checkOutDate = this.formatDateFun(this.data.selectedDateRange[1]);
        const nights = this.data.nights;
        
        wx.navigateTo({
            url: `/packageA/rooms/rooms?checkIn=${checkInDate}&checkOut=${checkOutDate}&nights=${nights}`
        });
    },

    /**
     * 搜索民宿
     */
    onSearch() {
        wx.showToast({
            title: '搜索功能开发中',
            icon: 'none'
        })
    },

    /**
     * 跳转到日志页面
     */
    goToLogs() {
        wx.navigateTo({
            url: '/packageB/pages/logs/logs'
        })
    },

    /**
     * 跳转到个人资料页面
     */
    goToProfile() {
        wx.navigateTo({
            url: '/pages/profile/profile'
        })
    },

    /**
     * 跳转到设置页面
     */
    goToSettings() {
        wx.navigateTo({
            url: '/packageA/pages/settings/settings'
        })
    },



    /**
     * 跳转到订单页面
     */
    goToOrders() {
        wx.navigateTo({
            url: '/packageB/pages/order/order'
        })
    },

    /**
     * 切换图片动画状态
     */
    toggleImageAnimation() {
        this.setData({
            isImageAnimating: !this.data.isImageAnimating
        });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '山居民宿 - 远离expensive，静享自然',
            path: '/pages/index/index',
            imageUrl: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80'
        }
    }
})